import { useModel } from "@umijs/max"
import { App, Form, InputNumber, Popconfirm, Table, Typography } from "antd"
import React, { useEffect, useState } from "react"

interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
  editing: boolean
  dataIndex: string
  title: any
  inputType: "number" | "text"
  record: any
  index: number
  children: React.ReactNode
}

const EditableCell: React.FC<EditableCellProps> = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `请输入 ${title}!`
            }
          ]}
        >
          <InputNumber />
        </Form.Item>
      ) : (
        children
      )}
    </td>
  )
}

const ImageJointParamsForm: React.FC = () => {
  const [form] = Form.useForm()
  const { imageJointParams } = useModel("toolModel")
  const [editingKey, setEditingKey] = useState("")
  const { callPy, wsIsOpenRef } = useModel("websocketModel")
  const { message } = App.useApp()
  const [isReload, setIsReload] = useState(true)

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await callPy("cameraTool", "get_image_joint_params_from_web", [])
        if (!response.state) {
          message.error("获取相机参数失败:" + response.info)
        }
      } catch (error) {
        console.log("数据加载失败", error)
      }
    }

    if (wsIsOpenRef.current) {
      fetchData()
    }
  }, [isReload])

  const isEditing = (record: any) => record.key === editingKey

  const edit = (record: any) => {
    form.setFieldsValue({ ...record })
    setEditingKey(record.key)
  }

  const cancel = () => {
    setEditingKey("")
  }

  const save = async (key: string) => {
    try {
      const row = await form.validateFields()
      const newData = { ...row, key }
      const response = await callPy("cameraTool", "save_joint_params_from_web", [newData])
      if (response.state) {
        setIsReload(!isReload)
        message.success("保存成功")
        setEditingKey("")
      } else {
        message.error("保存失败:" + response.info)
      }
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo)
    }
  }

  const columns = [
    {
      title: "左图左截",
      dataIndex: "leftCamStartOffset",
      editable: true,
      inputType: "number",
      ellipsis: true
    },
    {
      title: "左图右截",
      dataIndex: "leftCamEndOffset",
      editable: true,
      inputType: "number",
      ellipsis: true
    },
    {
      title: "右图左截",
      dataIndex: "rightCamStartOffset",
      editable: true,
      inputType: "number",
      ellipsis: true
    },
    {
      title: "右图右截",
      dataIndex: "rightCamEndOffset",
      editable: true,
      inputType: "number",
      ellipsis: true
    },
    {
      title: "左图上下截",
      dataIndex: "leftCamHOffset",
      editable: true,
      inputType: "number",
      ellipsis: true
    },
    {
      title: "操作",
      dataIndex: "operation",
      render: (_: any, record: any) => {
        const editable = isEditing(record)
        return editable ? (
          <span>
            <Typography.Link onClick={() => save(record.key)} style={{ marginRight: 8 }}>
              保存
            </Typography.Link>
            <Popconfirm title="确定取消?" onConfirm={cancel}>
              <a>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <Typography.Link disabled={editingKey !== ""} onClick={() => edit(record)}>
            编辑
          </Typography.Link>
        )
      }
    }
  ]

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col
    }
    return {
      ...col,
      onCell: (record: any) => ({
        record,
        inputType: "number",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record)
      })
    }
  })

  return (
    <Form form={form} component={false}>
      <Table
        components={{
          body: {
            cell: EditableCell
          }
        }}
        bordered
        dataSource={imageJointParams}
        columns={mergedColumns}
        rowClassName="editable-row"
        pagination={false}
      />
    </Form>
  )
}

export default () => (
  <App>
    <ImageJointParamsForm />
  </App>
)
